#include "StateMgr.h"
#include "State.h"
#include "Utils.h"

StateMgr::StateMgr()
{
	currentState = 0;
	nextState = 0;
}

StateMgr* StateMgr::GetInstance()
{
	if (instance == 0) 
	{ 
		PRINT("Init StateMgr\n");
		instance = new StateMgr(); 
	} 
	return instance;
}

void StateMgr::Update()
{
	// check if need switch state
	if (currentState != nextState)
	{
		if (currentState) 
		{
			currentState->Exit();
			if( currentState->isSingleton == true)
				currentState->Destroy();
			else DELETE_SAFELY(currentState);
		}
		if (nextState) 
		{
			nextState->Init();
		}
		currentState = nextState;
	}
}

void StateMgr::SwitchState(State* nextState)
{
	this->nextState = nextState;
}

State* StateMgr::GetCurrentState()
{
	return currentState;
}

StateMgr::~StateMgr()
{
	if( currentState->isSingleton == true)
		currentState->Destroy();
	else DELETE_SAFELY(currentState);
}

void StateMgr::Destroy()
{
	PRINT("Destroy StateMgr\n");
	DELETE_SAFELY(instance);
}

StateMgr* StateMgr::instance = 0;